/**
 * Created by zhengquan on 2017/10/30.
 */
$(function () {
    var deptList;//缓存树形部门列表
    var deptMap = {};//缓存最新一次的部门信息
    var userMap = {};//缓存最新一次的用户信息
    var optionStr = "";
    var lastClickDeptId = -1;//最新一次点击的部门id

    var deptListTemplate = $("#deptListTemplate").html();
    Mustache.parse(deptListTemplate);
    var userListTemplate = $("#userListTemplate").html();
    Mustache.parse(userListTemplate);

    loadDeptTree();
    bindDeptAddClick();
    bindUserAddClick();

    //加载树形部门列表
    function loadDeptTree() {
        $.ajax({
            url: '/sys/dept/tree.json',
            success: function (result) {
                if (result.ret) {
                    deptList = result.data;
                    var rendered = Mustache.render(deptListTemplate, {deptList: deptList});
                    $("#deptList").html(rendered);
                    recursiveRenderDept(deptList);
                    bindDeptClick();
                } else {
                    showMessage("加载部门列表", result.msg, false)
                }
            }
        })
    }

    //递归渲染部门树
    function recursiveRenderDept(deptList) {
        if (deptList && deptList.length > 0) {
            $(deptList).each(function (i, dept) {
                deptMap[dept.id] = dept;
                if (dept.list.length > 0) {
                    var rendered = Mustache.render(deptListTemplate, {deptList: dept.list});
                    $("#dept_" + dept.id).append(rendered);
                    recursiveRenderDept(dept.list);
                }
            })
        }
    }

    function bindDeptAddClick() {
        $(".dept-add").click(function () {
            $("#dialog-dept-form").dialog({
                modal: true,
                title: "新增部门",
                open: function (event, ui) {
                    $(".ui-dialog-titlebar-close", $(this).parent()).hide();
                    optionStr = "<option value=\"0\">-</option>";
                    recursiveRenderDeptSelect(deptList, 1);
                    $("#deptForm")[0].reset();
                    $("#parentId").html(optionStr);
                },
                buttons: {
                    "添加": function (e) {
                        e.preventDefault();
                        updateDept(true, function () {
                            $("#dialog-dept-form").dialog("close");
                            loadDeptTree();
                        }, function (data) {
                            showMessage("新增部门", data.msg, false);
                        });
                    },
                    "取消": function () {
                        $("#dialog-dept-form").dialog("close");
                    }
                }
            });
        });
    }

    //绑定部门点击操作
    function bindDeptClick() {
        $(".dept-delete").click(function (e) {
            e.preventDefault();
            e.stopPropagation();
            var deptId = $(this).attr("data-id");
            var deptName = $(this).attr("data-name");
            if (confirm("确定要删除部门【" + deptName + "】吗？")) {
                $.ajax({
                    url: '/sys/dept/delete.json',
                    data: {
                        id: deptId
                    },
                    success: function (result) {
                        if (result.ret) {
                            showMessage("删除部门【" + deptName + "】", "操作成功", false);
                            loadDeptTree();
                        } else {
                            showMessage("删除部门【" + deptName + "】", result.msg, false);
                        }
                    }

                })
            }

        });

        $(".dept-name").click(function (e) {
            e.preventDefault();
            e.stopPropagation();
            var deptId = $(this).attr("data-id");
            handleDeptSelected(deptId);
        });

        $(".dept-edit").click(function (e) {
            e.preventDefault();
            e.stopPropagation();
            var deptId = $(this).attr("data-id");
            $("#dialog-dept-form").dialog({
                modal: true,
                title: "编辑部门",
                open: function () {
                    $(".ui-dialog-titlebar-close", $(this).parent()).hide();
                    optionStr = "<option value=\"0\">-</option>";
                    recursiveRenderDeptSelect(deptList, 1);
                    $("#deptForm")[0].reset();
                    $("#parentId").html(optionStr);
                    $("#deptId").val(deptId);
                    var targetDept = deptMap[deptId];
                    if (targetDept) {
                        $("#parentId").val(targetDept.parentId);
                        $("#deptName").val(targetDept.name);
                        $("#deptSeq").val(targetDept.seq);
                        $("#deptRemark").val(targetDept.remark);
                    }
                },
                buttons: {
                    "更新": function (e) {
                        e.preventDefault();
                        updateDept(false, function () {
                            $("#dialog-dept-form").dialog("close");
                            loadDeptTree();
                        }, function (data) {
                            showMessage("更新部门", data.msg, false);
                        });
                    },
                    "取消": function () {
                        $("#dialog-dept-form").dialog("close");
                    }
                }
            });
        });
    }

    //递归渲染部门select树
    function recursiveRenderDeptSelect(deptList, level) {
        level = level | 0;
        if (deptList && deptList.length > 0) {
            $(deptList).each(function (i, dept) {
                deptMap[dept.id] = dept;
                var blank = "";
                if (level > 1) {
                    for (var j = 3; j <= level; j++) {
                        blank += "..";
                    }
                    blank += "┗";
                }
                optionStr += Mustache.render("<option value=\"{{id}}\">{{name}}</option>", {
                    id: dept.id,
                    name: blank + dept.name
                });
                if (dept.list && dept.list.length > 0) {
                    recursiveRenderDeptSelect(dept.list, level + 1);
                }

            })
        }
    }


    //更新部门操作
    function updateDept(isCreate, successCallback, failCallback) {
        $.ajax({
            url: isCreate ? '/sys/dept/save.json' : '/sys/dept/update.json',
            data: $("#deptForm").serialize(),
            type: 'post',
            success: function (result) {
                if (result.ret) {
                    if (successCallback)successCallback(result);
                } else {
                    if (failCallback)failCallback(result);
                }
            }
        });
    }


    //处理部门的选中效果
    function handleDeptSelected(deptId) {
        //移除原有部门的高亮样式
        if (lastClickDeptId != -1) {
            var lastDept = $("#dept_" + lastClickDeptId + " .dd2-content:first");
            lastDept.removeClass("btn-yellow");
            lastDept.removeClass("no-hover");
        }
        //添加当前部门的高亮样式
        var curDept = $("#dept_" + deptId + " .dd2-content:first");
        curDept.addClass("btn-yellow");
        curDept.addClass("no-hover");
        //缓存部门id
        lastClickDeptId = deptId;
        //加载用户列表
        loadUserList(deptId);
    }

    //加载用户列表
    function loadUserList(deptId) {
        var pageSize = $("#pageSize").val();
        var url = "/sys/user/page.json?deptId=" + deptId;
        var pageNo = $("#userPage .pageNo").val() || 1;
        $.ajax({
            url: url,
            data: {
                pageSize: pageSize,
                pageNo: pageNo
            },
            success: function (result) {
                renderUserListAndPage(result, url);
            }
        })
    }

    //渲染用户列表和分页信息
    function renderUserListAndPage(result, url) {
        if (result.ret) {
            if (result.data.total > 0) {
                var rendered = Mustache.render(userListTemplate, {
                    userList: result.data.data,
                    "showDeptName": function () {
                        return deptMap[this.deptId].name;
                    },
                    "showStatus": function () {
                        return this.state == 1 ? '有效' : (this.state == 0 ? '冻结' : '删除')
                    },
                    "bold": function () {
                        return function (text, render) {
                            var state = render(text);
                            if (state == '有效') {
                                return "<span class='label label-sm label-success'>" + state + "</span>"
                            } else if (state == '冻结') {
                                return "<span class='label label-sm label-warning'>" + state + "</span>"
                            } else {
                                return "<span class='label'>" + state + "</span>"
                            }
                        }
                    }
                });
                $("#userList").html(rendered);
                bindUserClick();
                $.each(result.data.data, function (i, user) {
                    userMap[user.id] = user;
                });
            } else {
                $("#userList").html('');
            }
            var pageSize = $("#pageSize").val();
            var pageNo = $("#userPage .pageNo").val() || 1;
            renderPage(url, result.data.total, pageNo, pageSize, result.data.total > 0 ? result.data.data.length : 0, "userPage", renderUserListAndPage)
        } else {
            showMessage("获取部门下用户列表", result.msg, false);
        }
    }

    function bindUserAddClick() {
        $(".user-add").click(function () {
            $("#dialog-user-form").dialog({
                modal: true,
                title: "新增用户",
                open: function (event, ui) {
                    $(".ui-dialog-titlebar-close", $(this).parent()).hide();
                    optionStr = "";
                    recursiveRenderDeptSelect(deptList, 1);
                    $("#userForm")[0].reset();
                    $("#deptSelectId").html(optionStr);
                },
                buttons: {
                    "添加": function (e) {
                        e.preventDefault();
                        updateUser(true, function () {
                            $("#dialog-user-form").dialog("close");
                            loadUserList(lastClickDeptId);
                        }, function (data) {
                            showMessage("新增用户", data.msg, false);
                        });
                    },
                    "取消": function () {
                        $("#dialog-user-form").dialog("close");
                    }
                }
            });
        });
    }

    //绑定用户点击操作
    function bindUserClick() {
        $(".user-acl").click(function (e) {
            e.preventDefault();
            e.stopPropagation();
            var userId = $(this).attr("data-id");
            $.ajax({
                url: '/sys/user/acls.json',
                data: {userId: userId},
                type: 'post',
                success: function (result) {
                    if (result.ret) {
                        console.log(result);
                    } else {
                        showMessage("获取用户权限数据", result.msg, false);
                    }
                }
            });
        });
        $(".user-edit").click(function (e) {
            e.preventDefault();
            e.stopPropagation();
            var userId = $(this).attr("data-id");
            $("#dialog-user-form").dialog({
                modal: true,
                title: "编辑部门",
                open: function () {
                    $(".ui-dialog-titlebar-close", $(this).parent()).hide();
                    optionStr = "";
                    recursiveRenderDeptSelect(deptList, 1);
                    $("#userForm")[0].reset();
                    $("#deptSelectId").html(optionStr);
                    $("#userId").val(userId);
                    var targetUser = userMap[userId];
                    if (targetUser) {
                        $("#deptSelectId").val(targetUser.deptId);
                        $("#userName").val(targetUser.username);
                        $("#userMail").val(targetUser.mail);
                        $("#userTelephone").val(targetUser.telephone);
                        $("#userStatus").val(targetUser.status);
                        $("#userRemark").val(targetUser.remark);
                        $("#userId").val(targetUser.id);
                    }
                },
                buttons: {
                    "更新": function (e) {
                        e.preventDefault();
                        updateUser(false, function () {
                            $("#dialog-user-form").dialog("close");
                            loadUserList(lastClickDeptId);
                        }, function (data) {
                            showMessage("更新用户", data.msg, false);
                        });
                    },
                    "取消": function () {
                        $("#dialog-user-form").dialog("close");
                    }
                }
            });
        });
    }

    //更新用户操作
    function updateUser(isCreate, successCallback, failCallback) {
        $.ajax({
            url: isCreate ? '/sys/user/save.json' : '/sys/user/update.json',
            data: $("#userForm").serialize(),
            type: 'post',
            success: function (reslut) {
                if (reslut.ret) {
                    if (successCallback)successCallback(reslut);
                } else {
                    if (failCallback)failCallback(reslut);
                }
            }
        });
    }
});